package com.example.demo.Controler.UserController;

import com.example.demo.Entity.User;
import com.example.demo.Service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import static com.example.demo.Errno.ErrnoDef.ERRNO_SUCCESS;


@RestController

public class RegisterController {
    static private final Logger logger = LoggerFactory.getLogger(RegisterController.class);
    @Autowired
    private UserService userService;
    /**
     * 用于声明注册时允许导入的有效参数的json
     * 对应 User 实体的属性
     */
    static String registerValidAttr_str = "["
            //+ "\"id\""
            + "  \"name\""
            + ", \"email\""
            + ", \"phonenumber\""
            + ", \"password\""
            //+ ", \"identity\""
            //+ ", \"status\""
            //+ ", \"createTime\""
            //+ ", \"gender\""
            //+ ", \"intro\""
            //+ ", \"avatar\""
            //+ ", \"organization\""
            //+ ", \"position\""
            //+ ", \"birthday\""
            //+ ", \"followingsNum\""
            //+ ", \"followersNum\""
            + "]";
    /**
     * 用于声明注册时允许导入的有效参数的列表，由json在初始化时转换而来
     * 对应 User 实体的属性
     */
    private static List<String> registerValidAttr;
    /**
     * 用于声明注册时允许导入的默认值的列表，由json在初始化时做转换
     * 对应 User 实体的属性，在注册前生成默认实体
     */
    static String registerDefaultAttr_str ="{"
            //+ "  \"id\""
            //+ ", \"name\""
            //+ ", \"email\""
            //+ ", \"phonenumber\""
            //+ ", \"password\""
            + " \"identity\":0"
            + ", \"status\":0"
            //+ ", \"createTime\""
            //+ ", \"gender\""
            //+ ", \"intro\""
            + ", \"avatar\":\"default.jpg\""
            //+ ", \"organization\""
            //+ ", \"position\""
            //+ ", \"birthday\""
            + ", \"followingsNum\":0"
            + ", \"followersNum\":0"
            + "}";
    /**
     * 该静态代码块 用于初始化声明 registerValidAttr 的有效参数的列表，由json转换
     *
     */
    static {

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            registerValidAttr = objectMapper.readValue(registerValidAttr_str, new TypeReference<List<String>>(){});
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
        }

    }
    /**
     * 注册api
     * @param req_map 请求对象
     * @return json串（字典），键值对：<br>
     * - errno：错误码 (0为无错误)<br>
     * - msg：错误信息
     */
    @PostMapping("/api/register")
    public Map<String,Object>register(@RequestBody Map<String,String> req_map){

        String name = req_map.get("name");
        Map<String,Object> map = new HashMap<>();
            try{
                User userdb = userService.selectUserByname(name);
                if(userdb != null){
                    map.put("errno",1001);
                    map.put("msg","用户名已注册");
                    return map;
                }else {
                    User regUser = null;
                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        regUser = objectMapper.readValue(registerDefaultAttr_str, User.class);
                    } catch (JsonProcessingException e) {
                        logger.error(e.getMessage());
                    }
                    for (String attr : registerValidAttr){
                        if(req_map.get(attr)!= null){
                            regUser.setAttribute(attr,req_map.get(attr));
                        }
                        else{
                            map.put("errno",1003);
                            map.put("msg","请填写必填项 " + attr);
                            return map;
                        }

                    }

                    userService.registerNewUser(regUser);
                    map.put("errno",ERRNO_SUCCESS.getErrno());
                    map.put("msg","注册成功");
                }
            }
            catch (Exception e){
                e.printStackTrace();
                map.put("errno",1002);
                map.put("msg","注册失败");
            }
            return map;
    }
}
